Go语言中的面向对象与传统的的面向对象编程有些不同,我们不去谈论Go语言中没有传统编程语言定义类所用的class关键字,而是使用类似C系语言的结构体,更多的是类似于以下的特性
以下例举Go语言与传统编程语言面向对象中的几大不同之处
1.子类调用父类方法影响的成员变量保留在父类体内
2.接口与接口之间的继承
3.一个类能实现多个接口中的抽象方法
子类调用父类方法影响的成员变量保留在父类体内
比如:传统的子类继承父类后,当子类与父类有相同的成员属性或者方法时,实例化子类,子类的方法和属性会被重写,这意味着子类的成员属性会覆盖父类,但是Go语言却有明显的不同。
如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package main import "fmt" type A struct {//父类A name string } func (this *A) setName(name string){//父类方法 this.name=name } type B struct {//子类B A //继承父类A name string } func main() { b:=new(B) b.setName("测试用户的名字") fmt.Println(b.name) //这里输出的是空字符串 fmt.Println(b.A.name) //这里输出的是:测试用户的名字 }<br /><br /> |
子类B继承了父类A,自然而然也继承了A类中的setName方法,但是在使用中的时候,请注意,B类调用setName方法,这个name属性值并没有被设置到B类中,可以很明显的看到是赋值到A类中了。
让我们进一步往下看
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package main import "fmt" type A struct { name string } func (this *A) setName(name string){ this.name=name } type B struct { A name string } func (this *B) setName(name string) { this.name=name } func main() { b:=new(B) b.setName("测试用户的名字") fmt.Println(b.name) //这里输出的是:测试用户的名字 fmt.Println(b.A.name) //这里输出的是:空字符串 b.A.setName("用户2号") fmt.Println(b.A.name) //输出:用户2号 } |
我们在子类B中将setName方法重写了,但是我们还是可以调用父类中的方法,给父类的成员属性name赋值
对以上一部分的总结:Golang中的继承,请先判断类中实现的方法是基于父类的继承还是子类自身实现的,如果是子类调用的方法继承于父类,那么该方法影响的成员属性,请去父类中查找。
其次谈谈接口与接口之间的继承
如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package main import "fmt" //接口1 type Interface1 interface { say() eat() } //接口2 type Interface2 interface { sleep() } //接口3 type Interface3 interface {<br /> //继承了接口1与接口2 Interface1 Interface2 } //定义一个类实现了,Interface3中的所有方法 type Human struct { } func (this *Human) say(){ fmt.Println("说话") } func (this *Human) eat(){ fmt.Println("吃东西") } func (this *Human) sleep(){ fmt.Println("睡觉") } func main() { var instance Interface3 var human *Human instance=human instance.say() } |
传统编程语言中,不存在接口被继承的说法,Go语言中,接口与接口之间还能继承,但是子接口继承父接口中不允许有相同的方法存在,即子接口不能重写父接口的抽象
一个类能实现多个接口中的抽象方法
从传统编程语言来看 ,一个类的定义只能实现一个接口内部的抽象方法,但是Go语言能让一个类实现多个接口
如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package main import "fmt" //动物接口 type Animal interface { eat() //吃东西方法 sleep() //睡觉方法 } //人类接口 type Human interface { say() //说话方法 } //定义学生类,实现以上2个接口中的抽象方法 type Student struct { } func (this *Student) say(){ fmt.Println("说话") } func (this *Student) eat(){ fmt.Println("吃饭") } func (this *Student) sleep(){ fmt.Println("睡觉") } func main() { var animal Animal var human Human student:=new(Student) human=student animal=student animal.eat() human.say() } |
从以上代码可以看出,学生类实现了动物接口同时也实现了人类接口
© 著作权归作者所有
文章评论(0)